<template>
  <div class="vehicle-application">
    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form-model layout="inline">
        <!-- 申请人 -->
        <!-- <a-form-model-item label="申请人">
          <a-tree-select v-model="searchForm.applicant_id" show-search style="width: 140px" treeNodeFilterProp="title"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="personListTree1"
            placeholder="请选择申请人">
          </a-tree-select>
        </a-form-model-item> -->
        <!-- 申请部门 -->
        <a-form-model-item label="申请部门">
          <a-select placeholder="请选择申请部门" v-model="searchForm.department_id" style="width:140px">
            <a-select-option :value="null">
              全部
            </a-select-option>
            <a-select-option v-for="item in departmentList" :key="item.department_id" :value="item.department_id">
              {{ item.department_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 用车人 -->
        <a-form-model-item label="用车人">
          <a-tree-select v-model="searchForm.passenger_id" show-search style="width: 140px" treeNodeFilterProp="title"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="personListTree1"
            placeholder="请选择用车人">
          </a-tree-select>
        </a-form-model-item>
        <!-- 目的地 -->
        <a-form-model-item label="目的地">
          <a-cascader :options="area" v-model="searchForm.destination" placeholder="请选择目的地" />
        </a-form-model-item>
        <!-- 审核状态 -->
        <a-form-model-item label="审核状态">
          <a-select v-model="searchForm.status" placeholder="审核状态" allowClear style="width: 120px">
            <a-select-option :value="null">全部</a-select-option>
            <a-select-option value="待审批">待审批</a-select-option>
            <a-select-option value="已批准">已批准</a-select-option>
            <a-select-option value="已拒绝">已拒绝</a-select-option>
            <a-select-option value="已取消">已取消</a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 用车日期 -->
        <a-form-model-item label="用车日期">
          <a-range-picker v-model="dateRange" :placeholder="['开始日期', '结束日期']" />
        </a-form-model-item>

        <a-form-model-item>
          <a-button type="primary" @click="handleSearch">
            查询
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <vxe-table ref="xTable" :loading="loading" :data="tableData" :auto-resize="true" :height="tableHeight" resizable
        show-overflow="tooltip">
        <vxe-column field="application_id" title="ID" width="60" />
        <vxe-column field="applicant_name" title="申请人" width="80" />
        <vxe-column field="department_name" title="申请部门" width="200" />
        <vxe-column field="passenger_names" title="用车人" width="200" />
        <vxe-column field="destination" title="目的地" width="200" />
        <vxe-column field="departure_date" title="出发日期" width="120">
          <template #default="{ row }">{{moment(row.departure_date).format('YYYY-MM-DD')}}</template>
        </vxe-column>
        <vxe-column field="departure_time_period" title="出发时间" width="80" />
        <vxe-column field="return_date" title="返回日期" width="120">
          <template #default="{ row }">{{moment(row.return_date).format('YYYY-MM-DD')}}</template>
        </vxe-column>
        <vxe-column field="return_time_period" title="返回时间" width="80" />
        <vxe-column field="reason" title="用车事由" min-width="120" />
        <vxe-column field="status" title="状态" width="100">
          <template v-slot="{ row }">
            <a-tag :color="getStatusColor(row.status)">
              {{ row.status }}
            </a-tag>
          </template>
        </vxe-column>
        <vxe-column field="apply_time" title="申请时间" width="180">
          <template #default="{ row }">{{moment(row.apply_time).format('YYYY-MM-DD HH:mm:ss')}}</template>
        </vxe-column>

        <vxe-column title="操作" width="220" fixed="right">
          <template v-slot="{ row }">
            <a-button type="link" size="small" @click="handleOpenDetail(row.application_id)">
              详情
            </a-button>
            <a-button v-if="canCancel(row)" type="link" size="small" style="color: #ff4d4f"
              @click="handleCancelModalOpen(row)">
              取消
            </a-button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination v-model="page.current" :total="page.total" :page-size="page.size"
          :page-size-options="['10', '20', '30', '40']" show-size-changer show-quick-jumper
          :show-total="total => `共 ${total} 条记录`" @change="handlePageChange" @showSizeChange="handleSizeChange" />
      </div>
    </div>

    <!-- 详情抽屉 -->
    <a-drawer title="详情" :width="720" :visible="detailVisible" :body-style="{ paddingBottom: '80px' }"
      @close="detailDrawerOnClose">
      <!-- 申请单信息 -->
      <a-form :form="baseInfo" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请人">
              <span>{{baseInfo.applicant_name}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话">
              <span>{{baseInfo.phone_number}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请部门">
              <span>{{baseInfo.department_name}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用车人">
              <span>{{passengers}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="出发时间">
              <span>{{moment(baseInfo.departure_date).format('YYYY-MM-DD')}} {{baseInfo.departure_time_period}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="返回时间">
              <span>{{moment(baseInfo.return_date).format('YYYY-MM-DD')}} {{baseInfo.return_time_period}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目的地">
              <span>{{baseInfo.destination}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用车事由">
              <span>{{baseInfo.reason}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请时间">
              <span>{{moment(baseInfo.apply_time).format('YYYY-MM-DD HH:mm:ss')}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态">
              <a-tag :color="getStatusColor(baseInfo.status)">
                {{ baseInfo.status }}
              </a-tag>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-divider>审核信息</a-divider>
      <!-- 审核信息 分配 -->
      <a-form v-if="(baseInfo.status === '待审批') && isAdmin" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="车辆">
              <a-select placeholder="请选择车辆" v-model="allocationsForm.vehicle_id">
                <a-select-option v-for="item in vehiclesList" :key="item.vehicle_id" :value="item.vehicle_id">
                  {{ item.vehicle_number }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="驾驶员">
              <a-select placeholder="请选择驾驶员" v-model="allocationsForm.driver_id">
                <a-select-option v-for="item in driversList" :key="item.driver_id" :value="item.driver_id">
                  {{ item.person_name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="审批意见" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-textarea v-model="approvalsForm.comment" placeholder="请输入审批意见"
                :auto-size="{ minRows: 3, maxRows: 5 }" />
            </a-form-item>
          </a-col>
          <a-col :span="24" :offset="4">
            <a-tag style="cursor-pointer" @click="approvalsForm.comment = '申请合理，予以批准'">申请合理，予以批准</a-tag>
            <a-tag style="cursor-pointer" @click="approvalsForm.comment = '申请冲突，不予批准'">申请冲突，不予批准</a-tag>
          </a-col>
          <a-col :span="24">
            <div style="float:right">
              <a-button :style="{ marginRight: '8px' }" @click="handleApprove('拒绝')" :loading="detailLoading">
                审批不通过
              </a-button>
              <a-button type="primary" @click="handleApprove('批准')" :loading="detailLoading">
                审批通过
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
      <!-- 审核信息 已审核 -->
      <a-form v-if="baseInfo.status !== '待审批'" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="车辆">
              <span>{{allocations[0] && allocations[0].vehicle_number}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="驾驶员">
              <span>{{allocations[0] && allocations[0].driver_name}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="审批意见">
              <span>{{approvals[0] && approvals[0].comment }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="审批人">
              <span>{{approvals[0] && approvals[0].approver_name}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="审批时间">
              <span>{{approvals[0] && moment(approvals[0].approval_time).format('YYYY-MM-DD HH:mm:ss')}}</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-divider v-if="baseInfo.status === '已取消'">取消信息</a-divider>
      <!-- 取消信息 -->
      <a-form v-if="baseInfo.status === '已取消'" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="取消原因">
              <span>{{cancelInfo.cancel_reason}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="取消人">
              <span>{{cancelInfo.canceler_name}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="取消时间">
              <span>{{ moment(cancelInfo.cancellation_time).format('YYYY-MM-DD HH:mm:ss')}}</span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-drawer>

    <!-- 取消弹窗 -->
    <a-modal title="确认取消" :visible="cancelVisible" :confirm-loading="cancelLoading" @ok="handleCancelConfirm"
      @cancel="cancelVisible = false">
      <a-textarea v-model="cancel_reason" placeholder="请输入取消原因" :auto-size="{ minRows: 3, maxRows: 5 }" />
    </a-modal>

    <!-- 下载弹窗 -->
  </div>
</template>

<script>
  import {
    apiPersonGetAllListTree,
    apiDepartmentList,
    apiVehicleApplicationList,
    apiVehicleApplicationAvailableVehicles,
    apiVehicleApplicationAvailableDrivers,
    apiVehicleApplicationDetailById,
    apiVehicleApplicationCancel,
    apiVehicleApplicationReview,
  } from '@/api/featch'

  import area from '@/assets/json/area.json'

  import moment from 'moment'

  export default {
    name: 'VehicleApplication',
    data() {
      return {
        moment, // 添加到data中
        // 搜索表单
        searchForm: {
          applicant_id: null,
          department_id: null,
          passenger_id: null,
          start_date: null,
          end_date: null,
          status: null,
          destination: null,
        },
        // 人员数
        personListTree1: [],
        personLoading: false,
        // 部门列表
        departmentList: [],
        area: area.options,
        // 日期范围
        dateRange: [],

        // 表格数据
        tableData: [],
        loading: false,
        tableHeight: null,

        // 分页信息
        page: {
          current: 1,
          size: 10,
          total: 0
        },

        /** 用户信息 */
        userInfo: {},
        // 当前用户ID
        currentUserId: null,

        /** 打开的弹窗信息 */
        detailLoading: false,
        // 车辆列表
        vehiclesList: [],
        // 驾驶员列表
        driversList: [],
        detailVisible: false,
        // 申请单信息
        baseInfo: {},
        // 审批表单
        approvalsForm: {
          comment: null,
        },
        // 审批信息
        approvals: [],
        // 分配表单
        allocationsForm: {
          vehicle_id: null,
          driver_id: null
        },
        // 分配信息
        allocations: [],
        // 用车人
        passengers: [],
        // 取消信息
        cancelInfo: {},

        /** 取消弹窗 */
        cancelId: null,
        cancelVisible: false,
        cancel_reason: null,
        cancelLoading: false,

        /** 下载弹窗 */
        downloadId: null,
        downloadVisible: false,
        downloadTable: [],
        downloadTableMergeCells: null
      }
    },
    computed: {
      isAdmin() {
        return this.userInfo.role_ov === '系统管理员'
      },
    },
    mounted() {
      // 表格高度
      this.initTableHeight()
      // 人员树
      this.getInitialPersonListTree()
      // 部门
      this.handleGetDepartmentList()
      // 获取车辆和驾驶员
      this.handleGetDriversAndVehicles()
      // 表格数据
      this.getTableData()
      // 权限检查
      this.checkUserRole()

      // 监听窗口大小变化
      window.addEventListener('resize', this.initTableHeight)
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.initTableHeight)
    },
    methods: {
      /**
       * @description 获取状颜色
       * '待审批','已批准','已拒绝','已取消'
       */
      getStatusColor(status) {
        const colorMap = {
          '待审批': 'orange',
          '已批准': 'green',
          '已拒绝': 'red',
          '已取消': '#f50',
        }
        return colorMap[status] || 'default'
      },
      /**
       * @description 初始化表格高度
       */
      initTableHeight() {
        const clientHeight = document.documentElement.clientHeight
        this.tableHeight = clientHeight - 64 - 48 - 132 - 44
      },
      /**
       * @description 获取初始人员列表 树状
       */
      async getInitialPersonListTree() {
        this.personLoading = true
        try {
          const res = await apiPersonGetAllListTree({})
          if (res.code === 200) {
            console.log(res.data)
            this.personListTree1 = [...res.data]
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.personLoading = false
      },
      /**
       * @description 获取部门列表
       */
      handleGetDepartmentList() {
        apiDepartmentList()
          .then(res => {
            if (res.code === 200) {
              this.departmentList = res.data
            }
          })
      },
      /**
       * @description 获取车辆和驾驶员
       */
      handleGetDriversAndVehicles() {
        apiVehicleApplicationAvailableVehicles()
          .then(res => {
            if (res.code === 200) {
              this.vehiclesList = res.data
            }
          })

        apiVehicleApplicationAvailableDrivers()
          .then(res => {
            if (res.code === 200) {
              this.driversList = res.data
            }
          })
      },
      /**
       * @description 获取表格数据
       */
      async getTableData() {
        this.loading = true
        try {
          const params = {
            page: this.page.current,
            page_size: this.page.size,
            applicant_id: this.searchForm.applicant_id,
            department_id: this.searchForm.department_id,
            passenger_id: this.searchForm.passenger_id,
            status: this.searchForm.status,
            start_date: this.dateRange.length ? moment(this.dateRange[0]).format('YYYY-MM-DD') : null,
            end_date: this.dateRange.length ? moment(this.dateRange[1]).format('YYYY-MM-DD') : null,
            destination: this.searchForm.destination ? this.searchForm.destination.join('/') : null,
          }
          const res = await apiVehicleApplicationList(params)
          if (res.code === 200) {
            this.tableData = res.data.list || []
            this.page.total = res.data.pagination.total || 0

            // 如果当前页没有数据且不是第一页，则跳转到上一页
            if (this.tableData.length === 0 && this.page.current > 1) {
              this.page.current--
              this.getTableData()
            }
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.loading = false
      },
      /**
       * @description 处理搜索
       */
      handleSearch() {
        this.page.current = 1
        this.getTableData()
      },
      /**
       * @description 重置搜索
       */
      handleReset() {
        this.searchForm = {
          applicant_id: null,
          department_id: null,
          passenger_id: null,
          start_date: null,
          end_date: null,
          status: null,
          destination: null,
        }
        this.dateRange = []
        this.handleSearch()
      },
      /**
       * @description 处理分页变化
       */
      handlePageChange(page) {
        this.page.current = page
        this.getTableData()
      },
      /**
       * @description 每页条数改变
       */
      handleSizeChange(current, size) {
        this.page.current = 1
        this.page.size = size
        this.getTableData()
      },
      /**
       * @description 打开取消弹窗
       */
      handleCancelModalOpen(row) {
        this.cancelId = row.application_id
        this.cancelVisible = true
      },
      /**
       * @description 处理取消
       */
      handleCancelConfirm() {
        if (!this.cancel_reason) {
          this.$message.warning('请输入取消原因')
          return
        }
        this.cancelLoading = true
        apiVehicleApplicationCancel({
            application_id: this.cancelId,
            canceler_id: this.currentUserId,
            cancel_reason: this.cancel_reason
          })
          .then(res => {
            this.cancelLoading = false
            if (res.code === 200) {
              this.$message.success('取消成功')
              this.cancelVisible = false
              this.getTableData()
            } else {
              this.$message.error(res.message)
            }
          }).catch(err => {
            this.$message.error(err.toString())
          })

      },
      /**
       * @description 打开详情弹窗
       */
      handleOpenDetail(application_id) {
        this.detailLoading = true
        this.detailVisible = true
        apiVehicleApplicationDetailById({
            application_id: application_id
          })
          .then(res => {
            this.detailLoading = false
            if (res.code === 200) {
              this.baseInfo = res.data.baseInfo
              this.approvals = res.data.approvals
              this.allocations = res.data.allocations
              this.passengers = Array.isArray(res.data.passengers) ? res.data.passengers.join(',') : ''
              this.cancelInfo = res.data.cancelInfo
            } else {
              this.$message.error(res.message)
            }
          })
      },
      detailDrawerOnClose() {
        this.detailVisible = false
      },
      /**
       * @description 处理审核
       */
      handleApprove(approval_result) {
        // 批准
        if (approval_result === '批准') {
          if (!this.allocationsForm.driver_id || !this.allocationsForm.vehicle_id || !this.approvalsForm.comment) {
            this.$message.warning('请选择车辆和驾驶员，并输入审批意见')
            return
          }
          this.detailLoading = true
          // 审批接口
          apiVehicleApplicationReview({
              application_id: this.baseInfo.application_id,
              approver_id: this.currentUserId,
              approval_result,
              comment: this.approvalsForm.comment,
              vehicle_id: this.allocationsForm.vehicle_id,
              driver_id: this.allocationsForm.driver_id,
            })
            .then(res => {
              this.detailLoading = false
              if (res.code === 200) {
                this.$message.success('审核完成')
                // 重新打开详情抽屉
                this.handleOpenDetail(this.baseInfo.application_id)
                // 重新获取列表
                this.getTableData()
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.detailLoading = false
            })
        }
        // 拒绝
        else {
          if (!this.approvalsForm.comment) {
            this.$message.warning('请输入审批意见')
            return
          }
          this.detailLoading = true
          // 审批接口
          apiVehicleApplicationReview({
              application_id: this.baseInfo.application_id,
              approver_id: this.currentUserId,
              approval_result,
              comment: this.approvalsForm.comment,
            })
            .then(res => {
              this.detailLoading = false
              if (res.code === 200) {
                this.$message.success('审核完成')
                // 重新打开详情抽屉
                this.handleOpenDetail(this.baseInfo.application_id)
              } else {
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.detailLoading = false
            })
        }
      },
      /**
       * @description 检查用户角色
       */
      checkUserRole() {
        // 获取用户信息
        const personInfo = window.sessionStorage.getItem('person_info')
        if (personInfo) {
          this.userInfo = JSON.parse(personInfo)
          this.currentUserId = this.userInfo.person_id
        }
      },
      /**
       * @description 检查是否可以删除
       */
      canCancel(row) {
        if (row.status === '已取消') {
          return false
        }
        if (row.status === '已拒绝') {
          return false
        }
        if (this.isAdmin) {
          return true
        }
        if (row.applicant_id === this.currentUserId) {
          return true
        }
        return false
      },
    }
  }
</script>

<style lang="less" scoped>
  .vehicle-application {
    height: 100%;

    .search-area {
      padding: 24px 24px 16px 24px;
      background: #fff;
      border-radius: 4px;
    }

    .table-area {
      background: #fff;
      padding: 0 24px;
      border-radius: 4px;

      .pagination-container {
        margin-top: 16px;
        text-align: right;
      }
    }
  }
</style>